// const axios = require('axios');
const axios = require('axios/dist/node/axios.cjs');
const fs = require('fs');
const path = require('path');
const https = require('https')
const { ipcMain } = require("electron")
const { readConfigFile } = require("@/utils/getBaseUrl")
const { parse, stringify } = require("flatted")
const store = require("../electronStore/index")
const { signature } = require("../utils/encrypt")
function createAxios() {
  const caPath = path.join(__dirname, '..', 'src', 'request', 'CNOOC ROOT RSACA.crt')
  console.log('caPath', caPath)
  // 读取 CA 证书文件
  const caCert = fs.readFileSync(caPath);
  // console.log('caCert', caCert.toString())
  // 创建 httpsAgent 并配置 CA 证书
  const httpsAgent = new https.Agent({
    ca: caCert,
  });
  // console.log('httpsAgent', httpsAgent)
  // console.log('axios', axios)
  // 创建自定义 Axios 实例
  const baseURL = `${readConfigFile().http_baseUrl}/api`;  // 直接拼接URL字符串
  const axiosInstance = axios.create({
    httpsAgent,
    baseURL,
    timeout: 1000000,
    headers: {
      'Content-Type': 'application/json'
    },
    withCredentials: true
  });

  // 请求拦截器
  axiosInstance.interceptors.request.use(
    async config => {
      // 每次发送请求之前判断是否存在token
      const token = store.get("token")
      const userName = store.get('userName')
      if (token) config.headers['token'] = token
      if (userName) {
        config.headers['Ks-Identity'] = await window.versions.getEncrypt(userName)
        config.headers["Client-Time"] = new Date().getTime()
      }
      config.headers['Ks-AppName'] = "electron"
      return config;
    },
    error => {
      return Promise.error(error);
    }
  )
  // 响应拦截器
  axiosInstance.interceptors.response.use(
    response => {
      let token = response.headers["token"];
      if (token) {
        store.set("token", token)
      }
      // 返回值为blob的特殊情况
      if (response.headers['content-type'] &&
        (response.headers['content-type'].search('octet/stream') > -1 ||
          response.headers['content-type'].search('octet-stream') > -1 ||
          response.headers['content-type'].search('application/pdf') > -1)) {
        return response.data;
      }
      if (response.status === 200 && (response.data.msg === 'SUCCESS' || response.data.msg === 'success')) {
        return Promise.resolve(response.data);
      } else {
        return Promise.reject(response.data);
      }
    },
  )
  return axiosInstance
}
function handerAxios() {
  const axiosInstance = createAxios()
  ipcMain.handle("createAxios", () => {
    return axiosInstance
  })
  ipcMain.handle('requestAxios', async (event, config) => {
    const params = parse(config)
    console.log('config', params);
    try {
      const response = await axiosInstance(params);
      console.log('res', response)
      let res
      if (params.responseType && params.responseType === 'arraybuffer') {
        // res = Buffer.from(response)
        res = response
        return res
      } else {
        res = response
        return stringify(res)
      }
      console.log('res', parse(stringify(res)));
    } catch (error) {
      console.log("error", error)
      return stringify({ error: error });
    }
  })
}

module.exports = {
  createAxios,
  handerAxios
};
